/**
 * Created by ruwang on 10/19/14.
 */
var SPLATTER_COMMON_AND_CONSTANTS = require('./ConstantAndCommon.js');

var getFileSize = function(path) {
    var fs = require("fs"); //Load the filesystem module
    var stats = fs.statSync(path);
    var fileSizeInBytes = stats["size"];
    fs = false;
    stats = false;
    return fileSizeInBytes;
}

var detectBufferSize = function(path) {
    var fileSize = getFileSize(path);
    var chunkCount = fileSize / global.config.MAX_BUFFER_TO_READ;
    var newBufferSize = global.config.MAX_BUFFER_TO_READ;

    console.log("[File] -> " + path);
    console.log("------------------------");
    console.log("[->] Size = " + fileSize);
    console.log("------------------------");
    if(SPLATTER_COMMON_AND_CONSTANTS.Constants.NUM.MAX_FILE_COUNT < chunkCount ) {
        var chunkCountTmp = chunkCount;
        while(SPLATTER_COMMON_AND_CONSTANTS.Constants.NUM.MAX_FILE_COUNT < chunkCountTmp) {
            chunkCount = chunkCountTmp ;
            chunkCountTmp = fileSize / ( newBufferSize );
            newBufferSize += global.config.BUFFER_SIZE_INCREMENT_VALUE;
        }
    }
    global.config.MAX_BUFFER_TO_READ = newBufferSize;
    console.log("[->] Chunks count = "+ chunkCount);
    console.log("[->] Buffer Size = "+ newBufferSize);
    console.log("[->] Config Value = "+ global.config.MAX_BUFFER_TO_READ);
    return newBufferSize;
}
var readByte = function(path) {
    console.log('[ '+(new Date())+'] -->Started');
    var fs = require('fs');
    var readStream = fs.createReadStream(path);

    readStream
        .on('readable', function () {
            var chunk;
            while (null !== (chunk =
                readStream.read(global.config.NUM.MAX_BUFFER_TO_READ))) {

            }
        })
        .on('end', function () {
            console.log('[ '+(new Date())+'] -->End');
            fs = false;
        });

    return true;
}

module.exports.FileBytes = readByte;
module.exports.FileSize = getFileSize;
module.exports.BufferSizeSet = detectBufferSize;